<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card class="box-card">
      <el-alert title="注意：只允许为第三级分类设置相关参数" type="warning" show-icon :closable="false">
      </el-alert>
      <!-- 选择商品分类区域 -->
      <el-row class="cat_opt">
        <!-- 级联选择框 -->
        <el-col>选择商品分类：
          <el-cascader v-model="selectedKeys" :options="cateList" @change="cateChange"
            :props="cateProps" clearable>
          </el-cascader>
        </el-col>

      </el-row>
      <!-- 标签页 -->
      <el-tabs v-model="activeName" @tab-click="handleClick">

        <!-- 动态参数标签页 -->
        <el-tab-pane label="动态参数" name="many">
          <el-row>
            <el-button type="primary" size="mini" :disabled="selectedKeys.length===0"
              @click="addDialogVisible=true">添加参数
            </el-button>
          </el-row>

          <!-- 动态参数表格 -->
          <el-table :data="manyTableData" border stripe>
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- 循环渲染tag标签 -->
                <el-tag class="attr_value" v-for="(item,index) in scope.row.attr_vals" :key="index"
                  closable @close="handleClose(index,scope.row)">{{item}}</el-tag>
                <!-- 新建标签 -->
                <el-input class="input-new-tag" v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue" ref="saveTagInput" size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)">
                </el-input>
                <el-button v-else size="small" @click="showInput(scope.row)">+ New Tag
                </el-button>
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scoped">
                <el-button type="primary" icon="el-icon-edit" size="mini"
                  @click="showEditDialog(scoped.row.attr_id)">
                  编辑
                </el-button>
                <el-button type="danger" icon="el-icon-delete" size="mini"
                  @click="removeParams(scoped.row.attr_id)">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <!-- 静态参数标签页 -->
        <el-tab-pane label="静态属性" name="only">
          <el-row>

            <el-button type="primary" size="mini" :disabled="selectedKeys.length===0"
              @click="addDialogVisible=true">添加属性
            </el-button>

          </el-row>
          <!-- 静态参数表格 -->
          <el-table :data="onlyTableData" border stripe>
           <!-- 展开行 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- 循环渲染tag标签 -->
                <el-tag class="attr_value" v-for="(item,index) in scope.row.attr_vals" :key="index"
                  closable @close="handleClose(index,scope.row)">{{item}}</el-tag>
                <!-- 新建标签 -->
                <el-input class="input-new-tag" v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue" ref="saveTagInput" size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)">
                </el-input>
                <el-button v-else size="small" @click="showInput(scope.row)">+ New Tag
                </el-button>
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column label="属性名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scoped">
                <el-button type="primary" icon="el-icon-edit" size="mini"
                  @click="showEditDialog(scoped.row.attr_id)">
                  编辑
                </el-button>
                <el-button type="danger" icon="el-icon-delete" size="mini"
                  @click="removeParams(scoped.row.attr_id)">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

      </el-tabs>
    </el-card>

    <!-- 通用添加对话框（动态参数，静态属性） -->
    <el-dialog :title="'添加'+dialogTitle" :visible.sync="addDialogVisible" width="50%"
      @close="addDialogClosed">
      <!-- 通用表单 -->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="120px">
        <el-form-item :label="dialogTitle" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 通用修改对话框（动态参数，静态属性） -->
    <el-dialog :title="'修改'+dialogTitle" :visible.sync="editDialogVisible" width="50%"
      @close="editDialogClosed">
      <!-- 通用表单 -->
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="120px">
        <el-form-item :label="dialogTitle" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { log } from 'util'
import { async } from 'q'
export default {
  data() {
    return {
      cateList: [],
      // 级联菜单选项已选
      selectedKeys: [],
      // 级联菜单选项
      cateProps: {
        label: 'cat_name',
        value: 'cat_id',
        children: 'children',
        expandTrigger: 'hover'
      },
      // 被激活的页签名称
      activeName: 'many',
      // 动态属性数组
      manyTableData: [],
      // 静态属性数组
      onlyTableData: [],
      // 通用添加对话框显示隐藏
      addDialogVisible: false,
      // 通用添加对话框表单
      addForm: {
        attr_name: ''
      },
      // 通用添加对话框表单验证规则
      addFormRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' }
        ]
      },
      // 编辑对话框显示隐藏
      editDialogVisible: false,
      editForm: {
        attr_name: ''
      },
      editFormRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    // 已选中的分类id
    cateId() {
      if (this.selectedKeys.length === 3) {
        return this.selectedKeys[2]
      }
      return null
    },
    // 通用对话框标题
    dialogTitle() {
      if (this.activeName === 'many') {
        return '动态参数'
      }
      return '静态属性'
    }
  },
  created() {
    this.getCateList()
  },
  methods: {
    // 获取所有的商品分类列表
    async getCateList() {
      const { data: res } = await this.$http.get('categories')

      if (res.meta.status !== 200) {
        return this.$message.error('获取商品分类列表失败')
      }

      this.cateList = res.data

      // console.log(res.data);
    },

    // 获取参数的列表数据
    async getParamsData() {
      // 要求必须选择三级分类，这里判断选择的数组，如果长度不是3，则取消选项
      if (this.selectedKeys.length !== 3) {
        this.selectedKeys = []
        this.manyTableData=[],
        this.onlyTableData=[]
        return
      }

      // 根据所选cateId和当前标签名发起请求
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes`,
        {
          params: {
            sel: this.activeName
          }
        }
      )

      if (res.meta.status !== 200) {
        return this.$message.error('获取参数列表失败')
      }

      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []

        // 给每一项设置默认新建标签的属性，显示隐藏，输入内容，防止冲突
        item.inputVisible = false
        item.inputValue = ''
      })

      // 判断参数列表渲染到那个表格
      if (this.activeName === 'many') {
        this.manyTableData = res.data
      } else {
        this.onlyTableData = res.data
      }

      // console.log(res.data)
    },

    // 级联菜单变化事件函数

    cateChange() {
      this.getParamsData()

    },
    // 标签页切换事件
    handleClick() {
      // console.log(this.activeName)
      this.getParamsData()
    },

    // 通用添加对话框关闭事件，重置表单
    addDialogClosed() {
      this.$refs.addFormRef.resetFields()
    },

    // 通用添加对话框确定按钮
    addParams() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return

        const { data: res } = await this.$http.post(
          `categories/${this.cateId}/attributes`,
          {
            attr_name: this.addForm.attr_name,
            attr_sel: this.activeName
          }
        )

        if (res.meta.status !== 201) {
          return this.$message.error('添加属性数据失败')
        }

        // 修改成功，三个操作
        // 提示修改成功，关闭对话框，更新数据列表
        this.$message.success('添加属性数据成功')
        this.addDialogVisible = false

        // console.log(res.data)

        this.getParamsData()
      })
    },

    // 点击修改弹出窗口
    async showEditDialog(attr_id) {
      // console.log(attr_id)

      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes/${attr_id}`,
        {
          params: {
            attr_sel: this.activeName
          }
        }
      )

      if (res.meta.status !== 200) {
        return this.$message.error('通过id获取属性失败')
      }

      this.editForm = res.data

      this.editDialogVisible = true
    },

    editDialogClosed() {
      this.$refs.editFormRef.resetFields()
    },

    //点击修改确定按钮
    editParams() {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return

        const { data: res } = await this.$http.put(
          `categories/${this.cateId}/attributes/${this.editForm.attr_id}`,
          {
            attr_name: this.editForm.attr_name,
            attr_sel: this.activeName
          }
        )

        if (res.meta.status !== 200) {
          // console.log(res)
          return this.$message.error('修改属性数据失败')
        }

        // 修改成功，三个操作
        // 提示修改成功，关闭对话框，更新数据列表
        this.$message.success('修改属性数据成功')
        this.editDialogVisible = false

        // console.log(res.data)

        this.getParamsData()
      })
    },

    // 删除属性
    removeParams(attr_id) {
      this.$confirm('此操作将永久删除该属性, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const { data: res } = await this.$http.delete(
            `categories/${this.cateId}/attributes/${attr_id}`
          )

          if (res.meta.status !== 200) {
            return this.$message.error('删除属性失败')
          }

          this.$message.success('删除成功!')
          this.getParamsData()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },

    // 通用修改attr_values
    async saveAttrValues(scope_row) {
      // 需要发起请求，保存此次修改数据
      const { data: res } = await this.$http.put(
        `categories/${this.cateId}/attributes/${scope_row.attr_id}`,
        {
          attr_name: scope_row.attr_name,
          attr_sel: scope_row.attr_sel,
          attr_vals: scope_row.attr_vals.join(' ')
        }
      )

      if (res.meta.status !== 200) {
        // console.log(res)
        return this.$message.error('修改标签属性数据失败')
      }

      this.$message.success('修改标签属性数据成功')
    },

    // 新建标签执行函数 （回车 or 移除焦点）
    handleInputConfirm(scope_row) {
      // 排除空格无效字符串,return
      if (scope_row.inputValue.trim().length === 0) {
        scope_row.inputValue = ''
        scope_row.inputVisible = false
        return
      }

      // 将inputvalue中的字符串添加到 attr_vals 的数组中
      scope_row.attr_vals.push(scope_row.inputValue.trim())
      scope_row.inputValue = ''
      scope_row.inputVisible = false
      this.editDialogVisible = false

      this.saveAttrValues(scope_row)

      
    },
    // 新建标签点击按钮
    showInput(scope_row) {
      scope_row.inputVisible = true
      // 让文本框自动获得焦点
      // $nextTick 当页面重新渲染后才执行这个方法
      // 防止input还没有渲染时，执行focus方法失效
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },

    // 属性标签关闭按钮，删除对应的可选项
    handleClose(index, scope_row) {
      scope_row.attr_vals.splice(index, 1)

      this.saveAttrValues(scope_row)
    }
  }
}
</script>

<style lang="less" scoped>
.cat_opt {
  margin: 15px 0;
}
.attr_value {
  margin-right: 10px;
  margin-bottom: 10px;
}
.input-new-tag {
  width: 100px;
}
</style>